import React, { useState, useEffect } from 'react';
import ContentTitle from "@/components/contentTitle/ContentTitle";
import { useSelector, useDispatch } from "react-redux";
import './center.less';
import { Flex, message, Upload } from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { changeInfor } from '@/store/userSlice';
import { baseUrl } from "@/utile/commen.js";
import { getUserInfo } from "@/api/users.js";
import moment from 'moment';

const beforeUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('You can only upload JPG/PNG file!');
    return Promise.reject();
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
    return Promise.reject();
  }
  return Promise.resolve();
};

export default function AccountCenter() {
  const dispatch = useDispatch();
  const [userInfo, setUserInfo] = useState({
    id: '',
    ctime: '',
    account: '',
    userGroup: '',
    imgUrl: ''
  });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const getUserId = () => {
    try {
      const user = JSON.parse(sessionStorage.getItem('user'));
      return user ? user.id : null;
    } catch (e) {
      return null;
    }
  };

  const getToken = () => {
    try {
      const user = JSON.parse(sessionStorage.getItem('user'));
      return user ? user.token : null;
    } catch (e) {
      return null;
    }
  };

  const uId = getUserId();

  const getInfo = async () => {
    if (!uId) {
      setError('无法获取用户ID');
      return;
    }
    try {
      const res = await getUserInfo({ id: uId });
      setUserInfo({...res.accountInfo,ctime:moment(res.accountInfo.ctime).format('YYYY-MM-DD HH:mm:ss')});
    } catch (e) {
      setError('获取用户信息失败');
      console.error(e);
    }
  };

  useEffect(() => {
    getInfo();
  }, []);

  const handleChange = async (info) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      getInfo();
      const updatedUserInfo = { ...userInfo, imgUrl: info.file.response.imgUrl };
      dispatch(changeInfor(updatedUserInfo));
      setLoading(false);
    }
    if (info.file.status === 'error') {
      setLoading(false);
      message.error('Upload failed!');
    }
  };

  const uploadButton = (
    <button style={{ border: 0, background: 'none' }} type="button">
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </button>
  );

  const token = getToken();

  return (
    <>
      <ContentTitle title="个人中心" />
      {error ? (
        <div className="error-message">{error}</div>
      ) : userInfo.id ? (
        <div className='account-center'>
          <div className="infoRow user-id">用户id：{userInfo.id}</div>
          <div className="infoRow">用户名：{userInfo.account}</div>
          <div className="infoRow">用户组：{userInfo.userGroup}</div>
          <div className="infoRow">创建时间：{userInfo.ctime}</div>
          <div>用户头像：</div>
          <Flex gap='middle' wrap>
            <Upload
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              action={"/poo/users/avatar_upload?id=" + userInfo.id}
              beforeUpload={beforeUpload}
              headers={token ? { Authorization: `Bearer ${token}` } : {}}
              onChange={handleChange}
            >
              {userInfo.imgUrl ? (
                <img src={baseUrl + userInfo.imgUrl} alt="avatar" style={{ width: '100%' }} />
              ) : (
                uploadButton
              )}
            </Upload>
          </Flex>
        </div>
      ) : (
        <div className="loading-message">正在加载用户信息...</div>
      )}
    </>
  );
}    